package com.geek.javaCource.demo;

import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * Create by chenhd on 2021/9/26.
 */
@Component
public class InsertService {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Transactional
    @ShardingTransactionType(TransactionType.XA)
    public void insert() {
        jdbcTemplate.execute("INSERT INTO t_order (order_id, total_price) VALUES (?, ?)", (PreparedStatementCallback<Object>) ps -> {
            ps.setObject(1, 1);
            ps.setObject(2, 100);
            ps.executeUpdate();
            return ps;
        });

        jdbcTemplate.execute("INSERT INTO t_order (order_id, total_price) VALUES (?, ?)", (PreparedStatementCallback<Object>) ps -> {
            ps.setObject(1, 2);
            ps.setObject(2, 200);
            ps.executeUpdate();
            return ps;
        });
    }
}
